<template>
  <MainLayout>
    <div class="checkout-content">
      <h2>结算页面</h2>
      
      <el-row :gutter="30">
        <!-- 订单信息 -->
        <el-col :span="16">
          <el-card>
            <template #header>
              <span>收货信息</span>
            </template>
            
            <el-form :model="orderForm" label-width="100px">
              <el-form-item label="收货人">
                <el-input v-model="orderForm.name" placeholder="请输入收货人姓名" />
              </el-form-item>
              <el-form-item label="手机号码">
                <el-input v-model="orderForm.phone" placeholder="请输入手机号码" />
              </el-form-item>
              <el-form-item label="收货地址">
                <el-input v-model="orderForm.address" type="textarea" :rows="3" placeholder="请输入详细地址" />
              </el-form-item>
              <el-form-item label="备注">
                <el-input v-model="orderForm.remark" type="textarea" :rows="2" placeholder="选填" />
              </el-form-item>
            </el-form>
          </el-card>

          <el-card style="margin-top: 20px">
            <template #header>
              <span>订单商品</span>
            </template>
            
            <el-table :data="cartItems" style="width: 100%">
              <el-table-column prop="image" label="商品" width="100">
                <template #default="scope">
                  <el-image :src="scope.row.image" style="width: 80px; height: 80px" fit="cover" />
                </template>
              </el-table-column>
              <el-table-column prop="name" label="商品名称" />
              <el-table-column prop="price" label="单价" width="100">
                <template #default="scope">¥{{ scope.row.price }}</template>
              </el-table-column>
              <el-table-column label="数量" width="100">
                <template #default="scope">{{ scope.row.quantity }}</template>
              </el-table-column>
              <el-table-column label="小计" width="100">
                <template #default="scope">
                  ¥{{ (scope.row.price * scope.row.quantity).toFixed(2) }}
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </el-col>

        <!-- 订单汇总 -->
        <el-col :span="8">
          <el-card class="order-summary">
            <template #header>
              <span>订单汇总</span>
            </template>
            
            <div class="summary-item">
              <span>商品总额：</span>
              <span>¥{{ totalPrice.toFixed(2) }}</span>
            </div>
            <div class="summary-item">
              <span>运费：</span>
              <span>¥{{ shippingFee.toFixed(2) }}</span>
            </div>
            <el-divider />
            <div class="summary-item total">
              <span>实付款：</span>
              <span class="total-price">¥{{ finalPrice.toFixed(2) }}</span>
            </div>
            
            <el-button type="primary" size="large" @click="submitOrder" :loading="loading" class="submit-btn">
              提交订单
            </el-button>
          </el-card>
        </el-col>
      </el-row>
    </div>
  </MainLayout>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import MainLayout from '../layouts/MainLayout.vue'
import axios from 'axios'

const router = useRouter()

const cartItems = ref([])
const loading = ref(false)

const orderForm = ref({
  name: '',
  phone: '',
  address: '',
  remark: ''
})

const shippingFee = ref(10) // 运费

const totalPrice = computed(() => {
  return cartItems.value.reduce((sum, item) => sum + item.price * item.quantity, 0)
})

const finalPrice = computed(() => {
  return totalPrice.value + shippingFee.value
})

const submitOrder = async () => {
  // 表单验证
  if (!orderForm.value.name || !orderForm.value.phone || !orderForm.value.address) {
    ElMessage.warning('请填写完整的收货信息')
    return
  }

  if (cartItems.value.length === 0) {
    ElMessage.warning('购物车为空')
    return
  }

  loading.value = true

  try {
    // 模拟提交订单
    await new Promise(resolve => setTimeout(resolve, 1500))
    
    // 创建订单数据
    const orderData = {
      items: cartItems.value,
      totalPrice: finalPrice.value,
      shippingFee: shippingFee.value,
      ...orderForm.value,
      orderId: 'ORD' + Date.now()
    }
    
    // 保存订单到localStorage（实际应该发送到服务器）
    const orders = JSON.parse(localStorage.getItem('orders') || '[]')
    orders.push(orderData)
    localStorage.setItem('orders', JSON.stringify(orders))
    
    // 清空购物车
    localStorage.removeItem('cart')
    
    ElMessage.success('订单提交成功！')
    
    // 跳转到订单详情或订单列表
    router.push(`/order/${orderData.orderId}`)
  } catch (error) {
    ElMessage.error('订单提交失败，请重试')
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  // 从localStorage加载购物车数据
  const savedCart = localStorage.getItem('cart')
  if (savedCart) {
    cartItems.value = JSON.parse(savedCart)
  }
  
  if (cartItems.value.length === 0) {
    ElMessage.warning('购物车为空，请先添加商品')
    router.push('/cart')
  }
})
</script>

<style scoped>
.checkout-content {
  padding: 20px 0;
}

.order-summary {
  position: sticky;
  top: 20px;
}

.summary-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 15px;
  font-size: 14px;
}

.summary-item.total {
  font-size: 18px;
  font-weight: bold;
}

.total-price {
  color: #f56c6c;
  font-size: 24px;
}

.submit-btn {
  width: 100%;
  margin-top: 20px;
  height: 50px;
  font-size: 18px;
}
</style>

